package com.thfw.test.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.StringRes;

/**
 * Created by litingwei on 2017/4/17.
 */
public class ToastUtils {

    private static Toast toast = null;

    public static void showToast(final Context context, final CharSequence text, final int duration) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (toast == null && context != null) {
                    toast = Toast.makeText(context.getApplicationContext(), text, duration);
                }
                if (toast != null) {
                    toast.setText(text);
                    toast.setDuration(duration);
                    toast.show();
                }
            }
        });
    }

    public static void showToast(final Context context, @StringRes final int resId, final int duration) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (toast == null) {
                    toast = Toast.makeText(context.getApplicationContext(), resId, duration);
                } else {
                    toast.setText(resId);
                    toast.setDuration(duration);
                }
                toast.show();
            }
        });
    }

    public static void showToast(Context context, CharSequence text) {
        showToast(context, text, Toast.LENGTH_SHORT);
    }

    public static void showToast(Context context, @StringRes int resId) {
        showToast(context, resId, Toast.LENGTH_SHORT);
    }

    public static void showToastLong(Context context, CharSequence text) {
        showToast(context, text, Toast.LENGTH_LONG);
    }

    public static void showToastLong(Context context, @StringRes int resId) {
        showToast(context, resId, Toast.LENGTH_LONG);
    }

}
